// #region ********** 变量 **********

var overlayList = []; // 图层列表
var chartList = []; // 图表列表
var currentChart = null; // 当前图表实例

// #endregion ********** 变量 **********

// #region ********** TwinIOC 初始化阶段 **********

// 创建并获取场景实例对象
function init() {
  window.tgTwinIOC = new twinIOC();
  let { url, locationId, token } = twiniocConfig;

  // 初始化地点
  tgTwinIOC.initLocation({ locationId, url, token }, (result) => {
    // console.log(result, '初始化地点接口');
  });

  // 注册地点加载完成时间
  tgTwinIOC.uniCall(
    'addEventListener',
    {
      eventName: 'locationInit',
      callback: () => {
        // 显示左侧面板
        document.querySelector('.left-panel-container').style.display = 'block';

        // 获取图层列表
        getOverlayList();
      },
    },
    (result) => {}
  );
}

// #endregion ********** TwinIOC 初始化阶段 **********

// #region ********** TwinIOC 相关操作 **********

// 获取图层列表
function getOverlayList() {
  tgTwinIOC.uniCall('getOverlayList', {}, (result) => {
    overlayList = result.data;

    renderOverlayList();
  });
}

// 设置图层显隐
function setOverlayVisibility(layerId, visible) {
  let jsonData = {
    layerId: layerId,
    visible: visible,
  };

  tgTwinIOC.uniCall('setOverlayVisibility', jsonData, (result) => {
    // console.log(result);
  });
}

// 获取图表列表
function getChartList() {
  tgTwinIOC.uniCall('getChartList', {}, (result) => {
    chartList = result.data;

    renderChartList();
  });
}

/**
 * 获取图表参数
 * @function getChartSetting
 *
 * @param {String} chartId - 图表 Id
 *
 */
function getChartSetting(chartId) {
  let jsonData = {
    chartId: chartId,
  };

  return new Promise((resolve, reject) => {
    tgTwinIOC.uniCall('getChartSetting', jsonData, (result) => {
      resolve(result);
    });
  });
}

// 点击图表列表
async function onChartItemClick(dom, chartId, chartName) {
  // 对象列表项的选中高亮状态
  document.querySelectorAll('.left-panel-container .chart .list-group-item').forEach((item) => {
    item.classList.remove('active');
  });
  dom.classList.add('active');

  let chartSetting = await getChartSetting(chartId);
  // console.log(chartSetting);

  // 显示右侧面板 设置标题
  document.querySelector('.right-panel-container').style.display = 'block';
  document.querySelector('.right-panel-container .title-name').innerHTML = chartName;

  // 渲染图表
  renderEchartsChart(chartSetting.data);
}

// #endregion ********** TwinIOC 相关操作 **********

// #region ********** HTML界面控件的事件处理函数 **********

// 点击tab菜单
function onLeftPanelTitleClick(tabName) {
  if (tabName === 'overlay') {
    getOverlayList();
  } else if (tabName === 'chart') {
    getChartList();
  }
}

// 渲染图层列表
function renderOverlayList() {
  let overlayListDom = document.querySelector('.left-panel.overlay');
  let overlayListStr = '';

  overlayList.forEach((item, index) => {
    let overlayStr = '';
    if (item.overlays && item.overlays.length) {
      item.overlays.forEach((overlayItem) => {
        overlayStr += `<li class="list-group-item" onclick="onOverlayItemClick(this, '${overlayItem.layerId}')"><span>${overlayItem.name}</span><div class="checkbox"><input type="checkbox" name="${overlayItem.layerId}" onclick="onChangeOverlayVisibility('${overlayItem.layerId}', this.checked)"></div></li>`;
      });
    }

    overlayListStr += `<div class="accordion-item">
    <h2 class="accordion-header">
      <div
        class="accordion-button"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#collapse${index}"
        aria-expanded="true"
        aria-controls="collapse${index}"
      >
        <span>${item.folderName}</span>

        <div class="accordion-header-right">
          <span class="icon-arrow">></span>
        </div>
      </div>
       <div class="all-checkbox">
          <input type="checkbox" name="${item.folderName}" value="${item.folderName}" onclick="onAllChangeOverlayVisibility('${item.folderName}', this.checked)">
        </div>
    </h2>
    <div id="collapse${index}" class="accordion-collapse collapse show" aria-labelledby="heading${index}">
      <div class="accordion-body">
        <ul class="list-group">
          ${overlayStr}
        </ul>
      </div>
    </div>
  </div>`;
  });

  overlayListDom.innerHTML = overlayListStr;
}

// 渲染图表列表
function renderChartList() {
  let chartListDom = document.querySelector('.left-panel.chart');
  let chartListStr = '';

  chartList.forEach((item, index) => {
    let chartStr = '';
    if (item.charts && item.charts.length) {
      // 按名称排序
      item.charts.sort((a, b) => a.categoryName.localeCompare(b.categoryName));

      item.charts.forEach((chartItem) => {
        chartStr += `<li class="list-group-item" onclick="onChartItemClick(this, '${chartItem.chartId}', '${chartItem.name}')">${chartItem.categoryName}：${chartItem.name}</li>`;
      });
    }

    chartListStr += `<div class="accordion-item">
    <h2 class="accordion-header">
      <div
        class="accordion-button"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#collapse${index}"
        aria-expanded="true"
        aria-controls="collapse${index}"
      >
        <span>${item.folderName}</span>

        <div class="accordion-header-right">
          <span class="icon-arrow">></span>
        </div>
      </div>
      
    </h2>
    <div id="collapse${index}" class="accordion-collapse collapse show" aria-labelledby="heading${index}">
      <div class="accordion-body">
        <ul class="list-group">
          ${chartStr}
        </ul>
      </div>
    </div>
  </div>`;
  });

  chartListDom.innerHTML = chartListStr;
}

// 渲染图表
function renderEchartsChart(chartData) {
  let chartDom = document.getElementById('chart-box');

  // 切换图表时如果当前图表实例存在，销毁重新创建
  if (currentChart) {
    currentChart.dispose();
    currentChart = null;
  }

  currentChart = echarts.init(chartDom);

  let option = {};
  // 根据图表类型设置不同的配置
  switch (chartData.chartType) {
    case '圆形仪表盘':
      option = {
        tooltip: {
          formatter: '{a} <br/>{b} : {c}%',
        },
        series: [
          {
            name: 'Pressure',
            type: 'gauge',
            radius: '90%',
            startAngle: 180,
            endAngle: 0,
            min: 0,
            max: 100,
            axisLine: {
              lineStyle: {
                width: 8,
                color: [[1, '#37a2da']],
              },
            },
            pointer: {
              itemStyle: {
                color: 'auto',
              },
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            detail: {
              valueAnimation: true,
              offsetCenter: [0, '40%'],
              fontSize: 30,
              fontWeight: 'bold',
              formatter: '{value}',
              color: '#fff',
            },
            title: {
              show: true,
              offsetCenter: [0, '80%'],
              color: '#fff',
              fontSize: 14,
            },
            data: [
              {
                value: chartData.style.quantitySize,
                name: chartData.style.unit,
              },
            ],
          },
        ],
      };
      break;
    case '数字仪表盘':
      option = {
        series: [
          {
            type: 'gauge',
            detail: {
              formatter: '{value}',
              color: '#fff',
              fontSize: 40,
              fontWeight: 'bold',
              offsetCenter: [0, '-10%'],
            },
            title: {
              show: true,
              offsetCenter: [0, '30%'],
              color: '#fff',
              fontSize: 14,
            },
            data: [
              {
                value: chartData.style.quantitySize,
                name: chartData.style.unit,
              },
            ],
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            pointer: {
              show: false,
            },
          },
        ],
      };
      break;
    default:
      chartDom.innerHTML = chartData.chartType + ' 暂未实现';
      break;
  }

  currentChart.setOption(option);
}

// 点击图层列表
function onOverlayItemClick(dom, layerId) {
  // console.log(dom, layerId);
}

// 点击图层复选框
function onChangeOverlayVisibility(layerId, visible) {
  setOverlayVisibility(layerId, visible);
}

// 点击菜单栏上的图表复选框 全部隐藏或显示
function onAllChangeOverlayVisibility(folderName, visible) {
  overlayList
    .find((item) => item.folderName === folderName)
    .overlays.forEach((overlayItem) => {
      setOverlayVisibility(overlayItem.layerId, visible);

      // 使下方的复选框根据当前的复选框状态进行勾选
      document.querySelector(`input[name="${overlayItem.layerId}"]`).checked = visible;
    });
}

// 关闭右侧面板
function closeRightPanel() {
  document.querySelector('.right-panel-container').style.display = 'none';
}

// #endregion ********** HTML界面控件的事件处理函数 **********

window.onload = function () {
  // 初始化
  // 1. 初始化孪易场景
  init();
};
